package groups.diseases.dao;

import groups.diseases.EtiologicalAgent;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

public class JDBCEtiologicalAgent implements IEtiologicalAgentDAO {
	private Connection connection;
	
	public JDBCEtiologicalAgent(Connection connection) throws SQLException{
		this.connection = connection;
	}
	
	
	@Override
	public EtiologicalAgent create(String name) throws SQLException {
		Statement stm = connection.createStatement();
		
		stm.executeUpdate("insert into EtiologicalAgent (name) values('"
				+name+"')");
		
		stm.close();
		stm = connection.createStatement();
		
		ResultSet res = stm.executeQuery("select max(idEtiologicalAgent),name from EtiologicalAgent group by idEtiologicalAgent");
		
		if(res.next())
			return new EtiologicalAgent(res.getInt(1), res.getString(name));
		else
			return null;
	}

	@Override
	public void update(EtiologicalAgent eti) throws SQLException {
		Statement stm = connection.createStatement();
		stm.executeUpdate("update EtiologicalAgent set name='"+eti.getName()+"'"+
		" where idEtiologicalAgent = " +eti.getId());
		
	}

	@Override
	public void delete(EtiologicalAgent eti) throws SQLException {
		Statement stm = connection.createStatement();
		stm.executeUpdate("delete from EtiologicalAgent"+
		" where idEtiologicalAgent = " +eti.getId());
	}

	@Override
	public Vector<EtiologicalAgent> getList() throws SQLException {
		Statement stm = connection.createStatement();
		
		ResultSet res = stm.executeQuery("select * from EtiologicalAgent");
		
		Vector<EtiologicalAgent> vec = new Vector<EtiologicalAgent>();
		
		while(res.next())
			vec.add(new EtiologicalAgent(res.getInt(1),res.getString(2)));
		
		return vec;
		
	}

	@Override
	public EtiologicalAgent getItem(int id) throws SQLException {
		Statement stm = connection.createStatement();
		
		ResultSet res = stm.executeQuery("select * from EtiologicalAgent where idEtiologicalAgent="+id);
		
		if(res.next())
			return new EtiologicalAgent(res.getInt(1),res.getString(2));
		else
			return null;
	}

}
